package chinaums.web.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import chinaums.common.util.Crypt;
import chinaums.dao.BankMapper;
import chinaums.dao.ConfigureMapper;
import chinaums.entity.Bank;
import chinaums.entity.CodeMsg;
import chinaums.entity.Rule;
import chinaums.plugin.redis.CacheClient;
import chinaums.service.IRuleService;
import chinaums.service.IRulesService;
import chinaums.service.impl.MessageListenerImpl;

import com.alibaba.fastjson.JSON;

/**
 * @author liyongjie
 * @date 2017年6月16日 上午9:21:27
 * @version v1.0
 * @description 主要是对规则编号在页面的展示修改添加及从数据库中读出数据按照要求把数据插入到redis服务器中
 */
@Controller
@RequestMapping("/show")
public class RuleController {
	private Logger logger = LoggerFactory.getLogger(RuleController.class);
	@Autowired
	private IRuleService rlueservice;
	@Resource(name = "jedisClientImpl")
	private CacheClient cacheClient;
	@Autowired
	private BankMapper bankMapper;
	@Autowired
	private ConfigureMapper Configuremapper;
	@Autowired
	private IRulesService RulesService;
	public static final String key = "31927HHdfsdfdsjdaD";//cookie加密密钥

	/*
	 * @Autowired private IBacrdService bacrdService;
	 * 
	 * @RequestMapping("/showBacrd") public String select(String bacrd){
	 * List<Bacrd> a=bacrdService.select_phone("6217232323357575"); for (int i =
	 * 0; i < a.size(); i++) { System.out.println(a.get(i).getB_phone()); }
	 * return bacrd; }
	 */
	/*
	 * 通过分页的方式在页面上面展示全部的规则编号信息
	 */
	@RequestMapping("/ShowRule1")
	public ModelAndView selectRule(HttpServletRequest request) throws UnsupportedEncodingException, Exception {
		ModelAndView mav = new ModelAndView("ShowRule");
		String jsonmap = getCardCheck(request);
		if(jsonmap==null || "".equals(jsonmap)){
			ModelAndView mav1 = new ModelAndView("redirect:/qrsms/login");
			return mav1;
		}
		return mav;
	}

	/*
	 * 展现规则编号的所有信息
	 */
	@RequestMapping("/ShowRuleDateils")
	public ModelAndView selectRuleDateils(HttpServletRequest request) throws UnsupportedEncodingException, Exception {
		ModelAndView mav = new ModelAndView("ShowRuleDateils");
		List<Map<String, Object>> list = RulesService.select_count();
		mav.addObject("list", list);
		String jsonmap = getCardCheck(request);
		if(jsonmap==null || "".equals(jsonmap)){
			ModelAndView mav1 = new ModelAndView("redirect:/qrsms/login");
			return mav1;
		}
		return mav;
	}

	/*
	 * 直接去redis里面插入键和值
	 */
	@RequestMapping("/addRedis")
	public void addRedises() {
		// cacheClient.setList("a", "b");
		// cacheClient.setList("a", "c");
		// cacheClient.setList("a", "d");
		// System.out.println("数值为："+cacheClient.getList("a"));
		// 将查出来的银行卡用list接收
		List<Bank> list = bankMapper.SelectBankAll();
		// 利用for循环往redis插值
		for (Bank bank : list) {
			System.out.println("^^^^^^^^^^^^^^^^^^^^^"
					+ bank.getQrsms_bankcard_card());
			// 调用set方法设置键值
			cacheClient.set("QRSMS_MQ_" + bank.getQrsms_bankcard_card(),
					bank.getQrsms_bankcard_card());
			System.out.println(cacheClient.get("QRSMS_MQ_"
					+ bank.getQrsms_bankcard_card()));
		}
	}

	/*
	 * 跳转至增加规则编号的页面
	 */
	@RequestMapping("/ShowRule4")
	public String orther() {
		return "../pages/Inserts";
	}

	/*
	 * 把qrsms_list表中的生命周期存放到redis中进行调用
	 */
	@RequestMapping("/ShowRule6")
	public String showa() {
		/*
		 * 1，根据方法把所有数据放到list中 2，遍历list获取其中某个字段的所有值 3，调用redis封装方法把字段 的值存放放在redis中
		 */
		// 值存放到集合中
		List<Map<String, String>> list = Configuremapper.ko();
		// 对集合进行遍历
		for (int i = 0; i < list.size(); i++) {
			System.out.println("结果为空：" + list.get(i).get("RULE_NUMBER"));
			System.out.println("结果为空：" + list.get(i).get("MARKETING_CYCLE"));
			// 进行数据redis存储
			// cacheClient.set(list.get(i).get("RULE_NUMBER"),
			// list.get(i).get("MARKETING_CYCLE"));
			cacheClient.del(list.get(i).get("RULE_NUMBER"));
		}
		/*
		 * for(int i=0;i<list.size();i++){ //map.put("", list.get(i)); map
		 * =list.get(i); System.out.println(map); JSONArray json =
		 * JSONArray.fromObject(map); String jsonString=json.toString();
		 * System.out.println(json); //cacheClient.set("a_"+i, jsonString);
		 * //cacheClient.del("a_"+i);
		 * System.out.println(jsonString+"…………………………"); }
		 */

		// System.out.println(map.get("marketing_cycle"));
		return "";
	}

	/*
	 * 展现规则的方法
	 */
	@RequestMapping(value = "/serchruls")
	public void serchruls(HttpServletRequest request,
			HttpServletResponse response, String QR_CONTENT,String QR_ID, Integer limit,
			Integer offset) throws Exception {
		response.setCharacterEncoding("utf-8");
		QR_CONTENT = request.getParameter("QR_CONTENT");
		logger.info("*********************获取到的值为："+QR_CONTENT);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("QR_CONTENT", "%" + QR_CONTENT + "%");// 模糊查询
		map.put("QR_ID", QR_ID);
		map.put("limit", offset + limit);
		map.put("offset", offset);
		/*String name = new String(request.getParameter("QR_CONTENT").getBytes(
				"iso8859-1"), "utf-8");
		logger.info("*********************获取到的值为："+name);
		// QR_CONTENT = request.getParameter("QR_CONTENT");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("QR_CONTENT", "%" + name + "%");// 模糊查询
		map.put("limit", offset + limit);
		map.put("offset", offset);*/
		
		List<Map<String, Object>> rows = RulesService.selectalls(map);// 获取列表
		long cnt = RulesService.rules_count(map);// 获取总数
		// long cnt = 2;//获取总数
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("rows", rows);
		resultMap.put("total", cnt);
		response.getWriter().print(JSON.toJSONString(resultMap));
		/*
		 * String str = JSON.toJSONString(resultMap); System.out.println(str);
		 * return str;
		 */
	}

	/*
	 * 插入规则的方法
	 */
	@RequestMapping(value = "/insertrule")
	public void insertset(HttpServletRequest request,
			HttpServletResponse response, String QR_CONTENT) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("QR_CONTENT", QR_CONTENT);
		CodeMsg msg = RulesService.insert_rules(map);// 新增方法
		response.getWriter().print(JSON.toJSONString(msg));
	}

	/*
	 * 修改规则的方法
	 */
	@RequestMapping(value = "/updaterule")
	public void updateset(HttpServletRequest request,
			HttpServletResponse response, String QR_ID, String QR_CONTENT,
			String QR_FLAG) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("QR_ID", QR_ID);
		map.put("QR_CONTENT", QR_CONTENT);
		map.put("QR_FLAG", QR_FLAG);
		CodeMsg rules = RulesService.update_rule(map);
		;// 配置修改方法
		response.getWriter().print(JSON.toJSONString(rules));
	}

	/*
	 * 删除规则的方法
	 */
	@RequestMapping(value = "/deleterule")
	public void deleteset(HttpServletRequest request,
			HttpServletResponse response, String QR_ID) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("QR_ID", QR_ID);
		// 根据ID删除配置
		CodeMsg msg = RulesService.delete_rule(map);
		response.getWriter().print(JSON.toJSONString(msg));
		/*
		 * String str = JSON.toJSONString(resultMap); System.out.println(str);
		 * return str;
		 */
	}

	/*
	 * 展现规则编号的方法
	 */
	@RequestMapping(value = "/serchrulsdate")
	public void serchrulsdate(HttpServletRequest request,
			HttpServletResponse response, String R_NUMBER, Integer limit,
			Integer offset) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("R_NUMBER", "%" + R_NUMBER + "%");// 模糊查询=%null%
		map.put("limit", offset + limit);
		map.put("offset", offset);
		List<Map<String, Object>> rows = rlueservice.selectall(map);// 获取列表

		long cnt = rlueservice.rules_count(map);// 获取总数
		// long cnt = 2;//获取总数
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("rows", rows);
		resultMap.put("total", cnt);
		response.getWriter().print(JSON.toJSONString(resultMap));
		/*
		 * String str = JSON.toJSONString(resultMap); System.out.println(str);
		 * return str;
		 */
	}

	/*
	 * 修改规则编号的方法
	 */
	@RequestMapping(value = "/updateruledate")
	public void updatesetdate(HttpServletRequest request,
			HttpServletResponse response, String R_RULE_ID, String R_ID,
			String R_NUMBER, String R_ORDER) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("R_RULE_ID", R_RULE_ID);
		map.put("R_ID", R_ID);
		map.put("R_NUMBER", R_NUMBER);
		map.put("R_ORDER", R_ORDER);
		CodeMsg rules = rlueservice.update_ruledate(map);// 配置修改方法
		response.getWriter().print(JSON.toJSONString(rules));
	}

	/*
	 * 删除规则编号的方法
	 */
	@RequestMapping(value = "/deleteruledate")
	public void deleteruledate(HttpServletRequest request,
			HttpServletResponse response, String R_RULE_ID) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("R_RULE_ID", R_RULE_ID);
		// 根据ID删除配置
		CodeMsg msg = rlueservice.delete_ruledate(map);
		response.getWriter().print(JSON.toJSONString(msg));
	}

	/*
	 * 插入规则编号的方法
	 */
	@RequestMapping(value = "/insertruledate")
	public void insertruledate(HttpServletRequest request,
			HttpServletResponse response, String R_ID, String R_NUMBER,
			String R_ORDER) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		R_ID = request.getParameter("R_ID");
		map.put("R_ID", R_ID);
		map.put("R_NUMBER", R_NUMBER);
		map.put("R_ORDER", R_ORDER);
		CodeMsg msg = rlueservice.insert_ruleq(map);// 新增方法
		response.getWriter().print(JSON.toJSONString(msg));
	}

	/*
	 * 测试调用
	 */
	@RequestMapping("/ShowRule23")
	public String updateRule() {
		// Configuremapper.update_number("130");
		// List<Map<String, Object>> map = RulesService.select_count();
		// for (int i = 0; i < map.size(); i++) {
		// System.out.println(map.get(i).get("QR_CONTENT"));
		// System.out.println(map.get(i).get("QR_ID"));
		// }
		/*Rule rule = rlueservice.select_exist("104");
		//Rule rulea = rlueservice.select_gid(String.valueOf(12));
		String r_number = String.valueOf(rule.getR_count());
		String a = String.valueOf(rule.getR_order());
		String aa = String.valueOf(rule.getR_rule_id());*/
		String r_number = "123123123奋斗的方式3213123";
		String a = "dhsakdsad曾经是卡的撒大苏打asdhaskldlasdsad";
		String aa = "***********************啊打手机看电视的！！！！！！！！！！！！！！！！！！";
		System.out.println("输出的数据最后显示为：" + r_number + ",显示的规则是：" + a + aa);

		return "ok";
	}

	// 判断数据库中是否有这个对象的方法
	@RequestMapping("/IsShow")
	@ResponseBody
	public String isexist(HttpServletRequest request) {
		String R_NUMBER = request.getParameter("R_NUMBER");
		Rule rule = rlueservice.select_exist(R_NUMBER);
		// String r_number = String.valueOf(map.get("R_NUMBER"));
		if (rule != null) {
			return "true";
		} else {
			return "false";
		}
	}
	
	//判断数据库中是否有这条规则的方法
	@RequestMapping("/IsShowGid")
	@ResponseBody
	public String isshowgid(HttpServletRequest request) {
		String R_ID = request.getParameter("R_ID");
		Rule rule = rlueservice.select_gid(R_ID);
		// String r_number = String.valueOf(map.get("R_NUMBER"));
		if (rule != null) {
			return "true";
		} else {
			return "false";
		}
	}
	//判断数据库中是否有条顺序的方法
	@RequestMapping("/IsShowOrder")
	@ResponseBody
	public String isShowgOrder(HttpServletRequest request) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		int R_ORDER = Integer.parseInt(request.getParameter("R_ORDER"));
		int R_ID = Integer.parseInt(request.getParameter("R_ID"));
		map.put("R_ORDER", R_ORDER);
		map.put("R_ID", R_ID);
		System.out.println("***"+map.get("R_ORDER"));
		System.out.println("***"+map.get("R_ID"));
		System.out.println("规则是："+R_ID);
		System.out.println("顺序是："+R_ORDER);
		Rule rule = rlueservice.select_order(map);
	
		// String r_number = String.valueOf(map.get("R_NUMBER"));
		if (rule != null) {
			return "true";
		} else {
			return "false";
		}
	}
	public static String getCardCheck(HttpServletRequest request) throws UnsupportedEncodingException, Exception{
	    	
	    	Cookie[] cookies = request.getCookies();  
	        if (cookies != null) {  
	            for (Cookie cookie : cookies) {  
	                if (("li").equals(cookie.getName())) {  
	                	String cookieStr =cookie.getValue();
	                	String uJsonDecode = URLDecoder.decode(cookieStr,"UTF-8");
	                	//byte[] ubyte = uJsonDecode.getBytes("UTF-8");
	                	byte[] ubyte = Base64.decodeBase64(uJsonDecode);
	        			String verifycode = new String(Crypt.decryptDES(ubyte,key),"UTF-8");
	        			return verifycode;
	                }  
	            }  
	        }  
	        return null;
	    }
	/*
	 * 按照条件查询相应的规则编号信息
	 */
	/*
	 * @RequestMapping("/ShowRule3") public ModelAndView selectRule1(int
	 * r_rule_id) { // 调用Service方法根据条件查询 Rule list =
	 * rlueservice.select_number(r_rule_id); ModelAndView mav = new
	 * ModelAndView(); mav.addObject("list", list);
	 * mav.setViewName("UpdateShowRule"); return mav; }
	 */

	/*
	 * 根据id修改相应的规则编号
	 */
	/*
	 * @RequestMapping("/ShowRule2") public String updateRule(String r_rule_id,
	 * String r_number) { // 通过实体类的set get方法实现修改 Rule rule = new Rule();
	 * rule.setR_number(r_number);
	 * rule.setR_rule_id(Integer.parseInt(r_rule_id)); int count =
	 * rlueservice.updateRule(rule); if (count > 0) { return
	 * "redirect:/show/ShowRule1"; } return "error"; }
	 */

	/*
	 * @RequestMapping(value = "/serchrulsdate") public void
	 * serchrulsdate(HttpServletRequest request, HttpServletResponse
	 * response,String R_NUMBER,Integer limit,Integer offset) throws Exception{
	 * Map<String,Object> map = new HashMap<String,Object>();
	 * map.put("R_NUMBER", "%"+R_NUMBER+"%");//模糊查询=%null% map.put("limit",
	 * offset+limit); map.put("offset", offset); List<Map<String,Object>> rows =
	 * rlueservice.selectall(map);//获取列表
	 * 
	 * long cnt = rlueservice.rules_count(map);//获取总数 //long cnt = 2;//获取总数
	 * Map<String,Object> resultMap = new HashMap<String,Object>();
	 * resultMap.put("rows", rows); resultMap.put("total", cnt);
	 * response.getWriter().print(JSON.toJSONString(resultMap)); String str =
	 * JSON.toJSONString(resultMap); System.out.println(str); return str; }
	 */

	/*
	 * 添加规则编号后返回展示规则编号的主页面
	 */
	/*
	 * @RequestMapping("/ShowRule5")
	 * 
	 * @ResponseBody public String insertall(HttpServletRequest request ) { //
	 * 通过map的put方法添加数据返回到主页面 String r_numbers1 =
	 * request.getParameter("r_numbers1");
	 * System.out.println("****************"+r_numbers1); Rule r_number =
	 * rlueservice.selectbynumber(r_numbers1);
	 * 
	 * if(r_number!=null){ return "false"; }else{ return "true"; }
	 */

	// return "redirect:/show/ShowRule1";
	// System.out.println("结果是："+r_number.getR_number());
	/*
	 * try { Rule r_number = rlueservice.selectbynumber(r_numbers1);
	 * 
	 * } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }
	 */
	/*
	 * System.out.println("****************"+r_orders);
	 * 
	 * System.out.println("****************"+r_ids);
	 */

	/*
	 * Map<String, Object> map = new HashMap<String, Object>(); int r_orders;
	 * int r_ids; map.put("r_number", r_numbers1); map.put("r_order", r_orders);
	 * map.put("r_id", r_ids); rlueservice.insert_all(map);
	 */
	// return "true";
	// }

	/*
	 * 展示id为1的所有规则编号
	 */
	/*
	 * @RequestMapping("/showalls") public void shoes() {
	 * 
	 * List<Bank> list = bankMapper.SelectBankAll(); for(int
	 * i=0;i<list.size();i++){ System.out.println("****************"+list.get
	 * (i).getQrsms_bankcard_card()); }
	 * 
	 * //
	 * System.out.println("*********************"+numbersMapper.select_order("104"
	 * ).getR_order()); //
	 * System.out.println("*********************"+z.select_order
	 * ("104").getR_order()); System.out.println("**************" +
	 * rlueservice.select_numbers(1).getR_order()); }
	 */

}
